package com.kuangstudy.wxpay.controller.login;

import com.google.gson.Gson;
import com.kuangstudy.wxpay.utils.HttpClientUtils;
import com.kuangstudy.wxpay.vo.R;
import lombok.extern.log4j.Log4j2;
import com.kuangstudy.wxpay.config.WeixinLoginProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 徐柯
 * @Title:
 * @Package
 * @Description:
 * @date 2021/4/2214:13
 */
@RestController
@Log4j2
@RequestMapping("/app")
public class ApiLoginController {

    @GetMapping("/wxlogin")
    public R callback(String code) {
        // 1：判断code是否合法
        if (StringUtils.isEmpty(code)) {
            return R.error().code(22008).message("登录失败，尝试刷新重新扫码登录!");
        }

        // 2：通过code获取access_token
        String baseAccessTokenUrl = WeixinLoginProperties.WX_OPEN_GATEWAY +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        log.info("1：openappid:{},appscrect:{}", WeixinLoginProperties.WX_OPEN_APP_ID, WeixinLoginProperties.WX_OPEN_APP_SECRET);
        //3：进行参数替换
        String accessTokenUrl = String.format(baseAccessTokenUrl, WeixinLoginProperties.WX_OPEN_APP_ID, WeixinLoginProperties.WX_OPEN_APP_SECRET, code);
        String result = null;
        try {
            //4：执行请求，获取微信请求返回得数据
            result = new HttpClientUtils().get(accessTokenUrl);
            log.info("2---->微信返回的日志信息是：code:{},result：{}", code, result);
            // 5： 对微信返回得数据进行转换
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(result, HashMap.class);
            log.info("3---->微信返回的日志信息是：code:{}，resultMap：{}", code, resultMap);
            if (resultMap.get("errcode") != null) {
                return R.error().code(22008).message("微信登录出错!");
            }

            // 6: 解析微信用户得唯一凭证openid
            String openid = (String) resultMap.get("openid");
            if (StringUtils.isEmpty(openid)) {
                return R.error().code(22009).message("登录失败，尝试刷新重新扫码登录!!");
            }

            // 7：接口返回openid
            return R.ok().data("openid", openid)
                    .data("resultMap",resultMap);

        } catch (Exception e) {
            return R.error().code(601).message("微信解析失败");
        }
    }
}
